<?php
define( program_recs_per_page,      6                                        );
define( admin_recs_per_page,        10                                       );
define( program_year_start,         2007                                     );
define( strmax,                     40                                       );
define( admin_email,                'tatyana.details@yandex.ru'              );               //sanda.gr@gmail.com'                     );
define( from_email,                 '<kyxna@details-moscow.ru>'              );
define( mail_request_subject,       'Мы получили вашу заявку'                );
define( mail_approve_subject,       'Подтверждаем ваше участие'              );
define( mail_deny_subject,          'К сожалению, отказ'                     );
define( mail_notification_subject,  'Заявка на участие в занятии'            );




global $menu, $months;
$months = array(
                  'Нулябрь',
                  'Январь',
                  'Февраль',
                  'Март',
                  'Апрель',
                  'Май',
                  'Июнь',
                  'Июль',
                  'Август',
                  'Сентябрь',
                  'Октябрь',
                  'Ноябрь',
                  'Декабрь'
);

$montha = array(
                  'Нулября',
                  'Января',
                  'Февраля',
                  'Марта',
                  'Апреля',
                  'Мая',
                  'Июня',
                  'Июля',
                  'Августа',
                  'Сентября',
                  'Октября',
                  'Ноября',
                  'Декабря'
);


  /**
   * Преобразовывает дату в формате Unix Timestamp
   * в форматирование MySQL
   *
   * @param int timestamp
   * @return date_string
   */
  function nix2mydate( $timestamp=NULL )
  {
    if ( empty($timestamp) )
      $timestamp = time();
    return strftime("%Y-%m-%d", $timestamp);
  }
  
  
  function my2nix($mydate)
  {
    $mydate = explode(" ", $mydate);
    $date = explode("-", $mydate[0]);
    $time = explode(":", $mydate[1]);
    return mktime($time[0]+0,$time[1]+0,$time[2]+0,$date[1]+0,$date[2]+0,$date[0]+0);
  }
 
  function mydate2nix($mydate)
  {
    $date = explode("-", $mydate);
    return mktime(23,0,0,$date[1]+0,$date[2]+0,$date[0]+0);
  }
 
  
  /**
   * Преобразовывает дату и время в формате Unix Timestamp
   * в форматирование MySQL
   *
   * @param int timestamp
   * @return date_string
   */
  function nix2my( $timestamp=NULL )
  {
    if ( empty($timestamp) )
      $timestamp = time();
    return strftime("%Y-%m-%d %T", $timestamp);
  }
  
  
  
  function format_text( $text ) {
    $text = str_replace( '<cut>', '', $text );
    $text = preg_replace( "/\n\s*\n/", "</p><p>", $text );
    $text = preg_replace( "/<\/h([1-7])>/", "</h\\1><p>", $text );
    $text = str_replace( "\n", "<br/>", $text );
    return "\n<p>\n" . $text . "\n</p>\n";
  }
  function cut( $text ) {
    $text = explode( '<cut>', $text );
    return $text[0];
  }
  
function zeros( $i ) {
  return (int)$i < 10 ? '0'.(int)$i : (string)$i;
}
  

  function template_ins ( $place, $item, $template )
  {
    if ( ( $i = strpos( $template, '{{'.$place.'}' ) ) || ( $i === 0 ))
      // сложная подстановка текста и подшаблона
      if ( $item )
      {
      	// текст не пустой, подставляем
        $i += strlen( '{{'.$place.'}' );
        for (   $count = 1 ;
                ( (bool) $count ) && ( isset( $template[$i] ) )
                ; ++$i )
        {
          if ( $template{$i} == "}" )
            --$count;
          if ( $template{$i} == "{" )
            ++$count;
          if ( ($count == 1 ) && ( $template{$i} == '%' ) )
            if ( substr( $template, $i, 7 ) == "%_here%" )
              $template = substr( $template, 0, $i ) . $item . substr( $template, $i + 7 );
            
        }
        $template[$i-1] = ' ';
        $template = str_replace( '{{'.$place.'}', '', $template );
      }
      else
      {
      	// текст пустой, затираем
        $s1 = substr( $template, 0, $i );
        $i += strlen( '{{'.$place.'}' );
        for (   $count = 1 ;
                ( (bool) $count ) && ( isset( $template[$i] ) )
                ; ++$i )
        {
          if ( $template[$i] == "}" )
            --$count;
          if ( $template[$i] == "{" )
            ++$count;
        }
        $template = $s1 . substr( $template, $i );
      }
    else
      // простая замена таргета текстом
      $template = str_replace( "{".$place."}", $item, $template );
    return $template;
  }


    
  class upload {
    public $f, $type, $filename, $error, $name;
    
    function __construct($f)
    {
      $this->file = is_string($f) ? $_FILES[$f] : $f;
      $type = explode(".", $this->file['name']);
      for ($i=1;!empty($type[$i]);$i++)
        $tmp = $type[$i];
      $this->type = strtolower(array_pop($type));
      $this->filename = translit(implode( '.', $type ));
      if ( empty( $this->filename ) ) {
        $this->filename = 'file';
      }
    }
  
    function save($path, $name = "", $tps = "all", $replace = true)
    {
  
      switch ($tps) {
        case "img":
          $types = array("jpeg", "jpg", "gif", "png");
          break;
        case "doc":
          $types = array("pdf", "doc", "pps");
          break;
        case "archive":
          $types = array("zip", "rar");
          break;
        case "all":
        default:
          $types = array(" ");
          break;
      }
      if ($path[strlen($path)-1] != "/")
        $path.= "/";
      if (empty($name)) {
        $name = $this->filename;
      }
      else
        $this->filename = $name;
      if (!empty($this->file["tmp_name"]))
      {
        if ((in_array($this->type,$types))||($tps=="all"))
        {
           while ((file_exists($path.$this->filename.".".$this->type))&&(!$replace))
             $this->filename.=rand(0,9);
           if (copy($this->file["tmp_name"], $path.$this->filename.".".$this->type))
             $this->error = 0;
           else
             $this->error = 1;
        }
        else
          $this->error = 2;
      }
      else
        $this->error = 3;
      $this->name = $this->filename . '.' . $this->type;
    }
    
    function error()
    {
      switch ($this->error) {
        case 0:
          return "Файл успешно загружен.";
        case 1:
          return "Файл _не_ сохранен.";
        case 2:
          return "Неверный тип файла.";
        case 3:
          return "Файл не загружен.";
      }
    }
  }
  

function dimensions($f) {
  $jpeg = array("jpeg", "JPEG", "jpg", "JPG");
  $gif = array("gif", "GIF");
  $png = array("PNG", "png");
  $type = explode(".", $f);
  $type = $type[count($type)-1];
  
  if (in_array($type, $jpeg))
    $im_src = imagecreatefromjpeg($f);
  if (in_array($type, $gif))
    $im_src = imagecreatefromgif($f);
  if (in_array($type, $png))
    $im_src = imagecreatefrompng($f);
  if (!empty($im_src))
  {
    $w = imagesx($im_src);
    $h = imagesy($im_src);
    return array($w, $h);
  }
}
function copyresizedw($f1, $f2, $w, $q=100) {
  $jpeg = array("jpeg", "JPEG", "jpg", "JPG");
  $gif = array("gif", "GIF");
  $png = array("PNG", "png");

  $type = explode(".", $f1);
  $type = $type[count($type)-1];
   
  $type2 = explode(".", $f2);
  $type2 = $type2[count($type2)-1];
    
  if (in_array($type, $jpeg))
    $im_src = imagecreatefromjpeg($f1);
  if (in_array($type, $gif))
    $im_src = imagecreatefromgif($f1);
  if (in_array($type, $png))
    $im_src = imagecreatefrompng($f1);
  if (!empty($im_src))
  {
    $w_src = imagesx($im_src);
    $h_src = imagesy($im_src);
    $ratio = $w_src/$w;
    $w_dest = round($w_src/$ratio);
    $h_dest = round($h_src/$ratio);
    $im_dest = imagecreatetruecolor($w_dest,$h_dest);
    imagecopyresampled($im_dest, $im_src, 0, 0, 0, 0, $w_dest, $h_dest, $w_src, $h_src);
    if (in_array($type2, $jpeg))
      imagejpeg($im_dest, $f2, $q);
    if (in_array($type2, $gif))
      imagegif($im_dest, $f2);
    if (in_array($type2, $png))
      imagepng($im_dest, $f2, $q);
  }
}

  function error()
  {
    switch ($this->error) {
      case 0:
        return "Файл успешно загружен.";
      case 1:
        return "Файл _не_ сохранен.";
      case 2:
        return "Неверный тип файла.";
      case 3:
        return "Файл не загружен.";
    }
  }

function copycropped($f1, $f2, $w, $h=NULL, $q=100)
{
  $h = $h ? $h : $w;
  $jpeg = array("jpeg", "JPEG", "jpg", "JPG");
  $gif = array("gif", "GIF");
  $png = array("PNG", "png");
  $bmp = array("BMP", "bmp");

  $type = explode(".", $f1);
  $type = $type[count($type)-1];

  $type2 = explode(".", $f2);
  $type2 = $type2[count($type2)-1];

  if (in_array($type, $jpeg))
  $im_src = imagecreatefromjpeg($f1);
  if (in_array($type, $gif))
  $im_src = imagecreatefromgif($f1);
  if (in_array($type, $png))
  $im_src = imagecreatefrompng($f1);
  if (in_array($type, $bmp)) {
    $im_src = imagecreatefrombmp($f1);
  }
  if (!empty($im_src))
  {
    $w_src = imagesx($im_src);
    $h_src = imagesy($im_src);
    $w_src2 = $w_src;
    $h_src2 = $h_src;
    $ratio1 = $h_src/$h;
    $ratio2 = $w_src/$w;
    $h_dest = $h;
    $w_dest = $w;
    if ( $ratio1 > $ratio2 )
    {
      $h_src = round($ratio2*$h_dest);
      $h = round(($h_src2-$h_src)/2);
      $im_dest = imagecreatetruecolor($w_dest,$h_dest);
      imagecopyresampled($im_dest, $im_src, 0, 0, 0, $h, $w_dest, $h_dest, $w_src, $h_src);
    }
    else
    {
      $w_src = round($ratio1*$w_dest);
      $w = round(($w_src2-$w_src)/2);
      $im_dest = imagecreatetruecolor($w_dest,$h_dest);
      imagecopyresampled($im_dest, $im_src, 0, 0, $w, 0, $w_dest, $h_dest, $w_src, $h_src);
    }
    if (in_array($type2, $jpeg))
    imagejpeg($im_dest, $f2, $q);
    if (in_array($type2, $gif))
    imagegif($im_dest, $f2);
    if (in_array($type2, $png))
    imagepng($im_dest, $f2, $q);
    //      echo '(((',$w,',',$ratio,',',$w_dest,',',$w_src,')))';
  }
}

function ConvertBMP2GD($src, $dest = false) {
if(!($src_f = fopen($src, "rb"))) {
return false;
}
if(!($dest_f = fopen($dest, "wb"))) {
return false;
}
$header = unpack("vtype/Vsize/v2reserved/Voffset", fread($src_f,
14));
$info = unpack("Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vimportant",
fread($src_f, 40));

extract($info);
extract($header);

if($type != 0x4D42) { // signature "BM"
return false;
}

$palette_size = $offset - 54;
$ncolor = $palette_size / 4;
$gd_header = "";
// true-color vs. palette
$gd_header .= ($palette_size == 0) ? "\xFF\xFE" : "\xFF\xFF";
$gd_header .= pack("n2", $width, $height);
$gd_header .= ($palette_size == 0) ? "\x01" : "\x00";
if($palette_size) {
$gd_header .= pack("n", $ncolor);
}
// no transparency
$gd_header .= "\xFF\xFF\xFF\xFF";

fwrite($dest_f, $gd_header);

if($palette_size) {
$palette = fread($src_f, $palette_size);
$gd_palette = "";
$j = 0;
while($j < $palette_size) {
$b = $palette{$j++};
$g = $palette{$j++};
$r = $palette{$j++};
$a = $palette{$j++};
$gd_palette .= "$r$g$b$a";
}
$gd_palette .= str_repeat("\x00\x00\x00\x00", 256 - $ncolor);
fwrite($dest_f, $gd_palette);
}

$scan_line_size = (($bits * $width) + 7) >> 3;
$scan_line_align = ($scan_line_size & 0x03) ? 4 - ($scan_line_size &
0x03) : 0;

for($i = 0, $l = $height - 1; $i < $height; $i++, $l--) {
// BMP stores scan lines starting from bottom
fseek($src_f, $offset + (($scan_line_size + $scan_line_align) *
$l));
$scan_line = fread($src_f, $scan_line_size);
if($bits == 24) {
$gd_scan_line = "";
$j = 0;
while($j < $scan_line_size) {
$b = $scan_line{$j++};
$g = $scan_line{$j++};
$r = $scan_line{$j++};
$gd_scan_line .= "\x00$r$g$b";
}
}
else if($bits == 8) {
$gd_scan_line = $scan_line;
}
else if($bits == 4) {
$gd_scan_line = "";
$j = 0;
while($j < $scan_line_size) {
$byte = ord($scan_line{$j++});
$p1 = chr($byte >> 4);
$p2 = chr($byte & 0x0F);
$gd_scan_line .= "$p1$p2";
} $gd_scan_line = substr($gd_scan_line, 0, $width);
}
else if($bits == 1) {
$gd_scan_line = "";
$j = 0;
while($j < $scan_line_size) {
$byte = ord($scan_line{$j++});
$p1 = chr((int) (($byte & 0x80) != 0));
$p2 = chr((int) (($byte & 0x40) != 0));
$p3 = chr((int) (($byte & 0x20) != 0));
$p4 = chr((int) (($byte & 0x10) != 0));
$p5 = chr((int) (($byte & 0x08) != 0));
$p6 = chr((int) (($byte & 0x04) != 0));
$p7 = chr((int) (($byte & 0x02) != 0));
$p8 = chr((int) (($byte & 0x01) != 0));
$gd_scan_line .= "$p1$p2$p3$p4$p5$p6$p7$p8";
} $gd_scan_line = substr($gd_scan_line, 0, $width);
}

fwrite($dest_f, $gd_scan_line);
}
fclose($src_f);
fclose($dest_f);
return true;
}

function imagecreatefrombmp($filename) {
$tmp_name = tempnam("upload/", "GD");
if(ConvertBMP2GD($filename, $tmp_name)) {
$img = imagecreatefromgd($tmp_name);
unlink($tmp_name);
return $img;
} return false;
}

  
  /**
   * Обертка для функции mail
   *
   * @param str $to
   * @param str $subject
   * @param str $message
   * @param str $headers
   * @return bool
   */
  function send_mail( $to, $subject, $message, $headers='' )
  {
    $message = str_replace( "\n", "<br>\n", $message );
    $subject = iconv( 'utf-8', 'koi8-r',$subject );
    $subject = $subject ? '=?koi8-r?B?'.base64_encode($subject).'?=' : '' ;
    $head  = "Content-type: text/html; charset=utf-8; \n";
    $head .= "From: ".from_email."\n";
    $head .= $headers;
    return mail( $to, $subject, $message, $head );
  }

?>